﻿#include <QTextStream>
#include <QFile>
#include <QDebug>
#include <QJsonValue>

#include "HtmlExport.h"
#include "FileUtils.h"

HtmlExport::HtmlExport(QObject *parent) : QObject(parent)
{

}

void HtmlExport::SetMeasureParam(QStringList headers, QStringList values)
{
    _measureParamHeader=GenerateTableHeader(headers);
    _measureParamValue=GenerateTableRow(values);
}

void HtmlExport::SetMeasureResult(QStringList headers, QStringList values)
{
    _measureResultHeader=GenerateTableHeader(headers);
    _measureResultValue=GenerateTableRow(values);
}

void HtmlExport::SetEachMeasureResult(QStringList headers, QList<QStringList> values)
{
    _measureEachResultHeader=GenerateTableHeader(headers);

    QStringList arr;
    for(QStringList item:values)
    {
        QString row=GenerateTableRow(item);
        arr.append(row);
    }
    _measureEachResultValue=arr.join("");
}

QString HtmlExport::Export(QString templateFn,QString targetFn)
{
    QString templateHtml=ReadTemplate(templateFn);
    templateHtml.replace("{{measureParamHeaders}}", _measureParamHeader);
    templateHtml.replace("{{measureParamValues}}", _measureParamValue);

    templateHtml.replace("{{measureResultHeaders}}", _measureResultHeader);
    templateHtml.replace("{{measureResultValues}}", _measureResultValue);

    templateHtml.replace("{{measureEachResultHeaders}}", _measureEachResultHeader);
    templateHtml.replace("{{measureEachResultValues}}", _measureEachResultValue);

    FileUtils::ExportToFile(templateHtml,targetFn);
    return templateHtml;
}

QString HtmlExport::ReadAndModifyTemplate(QString templateHtml, QString measureParamHeader,QString measureParamValue)
{
    templateHtml.replace("{{measureParamHeaders}}", measureParamHeader);
    templateHtml.replace("{{measureParamValues}}", measureParamValue);
    return templateHtml;
}

QString HtmlExport::GenerateTableHeader(QStringList Headers)
{
    QString ret;
    QTextStream stream(&ret);
    stream << "<tr>";
    for (QString value : Headers) {
        stream << "<th>" << value << "</th>";
    }
    stream << "</tr>";
    return ret;
}

QString HtmlExport::GenerateTableRow(QStringList values)
{
    QString ret;
    QTextStream stream(&ret);
    stream << "<tr>";
    for (QString value : values) {
        stream << "<td>" << value << "</td>";
    }
    stream << "</tr>";
    return ret;
}

QString HtmlExport::ReadTemplate(const QString &templatePath)
{
    return FileUtils::ReadFile(templatePath);
}
